<?php

namespace Frieza\Modules\creators\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\CreatorHotWord;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Facades\Validator;

class HotWordsController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $words = $request->input('words', '');
        if (!empty($words)) {
            $where['words[~]'] = $words;
        }
        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $where['word_status'] = CreatorHotWord::STATUS_NORMAL;
        $where['ORDER'] = 'word_sort';
        $list = CreatorHotWord::selectByWhere($where);
        $total = CreatorHotWord::selectCount($where);
        $gridModel = new pGridDataModel($list, $total, ['perPage' => $pageSize]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function (Grid\Filter $filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->equal('words', '热词');

                    if (!empty($condition)) {
                        $filter->expand();//默认展开
                    }
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'id')->sort();
                $grid->column('words', '热词');
                $grid->column('addtime', '添加时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->addtime);
                });
                $grid->column('edittime', '编辑时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->edittime);
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                });
            }
        );
        $tab = new Tab();
        $tab->add('热词列表', $gridList->render(), true);
        return $content->header('热词列表')->breadcrumb(
            ['text' => '热词列表'])
            ->row($tab);
    }


    public function create(Request $request, Content $content, $id = 0)
    {
        $header = '添加热词';
        if ($id) {
            $header = '编辑热词';
        }
        $info = $id ? CreatorHotWord::get('*', ['id' => $id, 'word_status' => CreatorHotWord::STATUS_NORMAL]) : [];
        $form = new Form($info);
        $form->hidden('id', '内容id');
        $form->text('words', '热词添加')->required()->help('最多输入20个字')->attribute('maxlength', '20');
        $form->action('/admin/creators/hot/add');
        return $content->header($header)->breadcrumb(
            ['text' => '热词列表', 'url' => url('admin/hot/index')],
            ['text' => $header])
            ->row($form->render());
    }


    public function add(Request $request)
    {
        $request = $request->all();
        $validator = Validator::make($request,
            [
                'words' => 'required|max:20',
            ]
        );
        if ($validator->fails() == true) {
            $error = new MessageBag([
                'title' => $validator->errors()->first()
            ]);
            return back()->with(compact('error'));
        }
        $one = CreatorHotWord::get('*', ['words' => $request['words'], 'state' => CreatorHotWord::STATUS_NORMAL]);
        $error = new MessageBag([
            'title' => '热词已存在'
        ]);
        unset($request['_token']);
        $request['admin_id'] = Admin::user()->id;
        if (isset($request['id']) && $request['id']) {
            if ($one != null && $one['id'] != $request['id']) {
                return back()->with(compact('error'));
            }
            //修改
            $result = CreatorHotWord::update($request, ['id' => $request['id']]);
            $num = $result->rowCount();
            if ($num > 0) {
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
                return redirect('/admin/creators/hot/index')->with(compact('success'));
            }
        } else {
            if ($one != null) {
                return back()->with(compact('error'));
            }
            unset($request['id']);
            $request['addtime'] = $request['edittime'] = time();
            $request['word_status'] = 1;
            $result = CreatorHotWord::insert($request);

            if ($result) {
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
                return redirect('/admin/creators/hot/index')->with(compact('success'));
            }
        }

        $error = new MessageBag([
            'title' => '保存失败'
        ]);
        return back()->with(compact('error'));

    }


    public function del($id)
    {
        $data = CreatorHotWord::get('*', ['id' => $id]);
        $data['word_status'] = CreatorHotWord::STATUS_DEL;
        $data['edittime'] = time();

        $rs = CreatorHotWord::update($data, ['id' => $id]);
        if ($rs->rowCount() > 0) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }

    }

    public function sort(Request $request)
    {
        $data = $request->input('sort');
        foreach ($data as $k => $v) {
            CreatorHotWord::update(['word_sort' => $v], ['id' => $k]);
        }
        return response()->json([
            'status' => true,
            'message' => "操作成功",
        ]);
    }
}